const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');
const pi = require('../../utils/piexif.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    newGoods: [],
    hotGoods: [],
    topics: [],
    brands: [],
    groupons: [],
    floorGoods: [],
    banner: [],
    channel: [],
    coupon: [],
    articles:[],
    goodsCount: 0,
    indicatorDots: false,
    window: false,
    colseCoupon:false,
    title: '',
    version: '',
    author_name: '',
    picUrls: [],
    files: [],
    picCanvasWidth: 0,
    picCanvasHeight: 0,
    buttonText: '查看 / 编辑'
  },

  resetCanvas(context,width,height){
    context.rect(0, 0, width, height - 4);  //画板大小
    context.setFillStyle('#fff');//背景填充
    context.fill()  //设置填充
    context.draw()    //开画
  },



  chooseImage: function(e) {
    
    this.setData({
      files: []
    })
    if (this.data.files.length >= 1) {
      util.showErrorToast('只能上传1张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        that.data.imageUploadProgress = 0
        that.setData({
          files: res.tempFilePaths
        });
        that.setData({
          buttonText: '解析图片中...'
        })

        wx.getImageInfo({
          src: res.tempFilePaths[0],
          fail(e){
            console.log(e)
            that.setData({
              buttonText: '解析失败，请重传'
            })
          },
          success (res) {
            console.log(res)
            if(res.type==='jpeg' || res.type==='tiff'){
              console.log('-------------no need convert---------')
              that.setData({
                buttonText: '查看 / 编辑'
              })
              return
            }else{
              console.log('-------------start convert---------')
            }
              //画入canvas
              const context = wx.createCanvasContext('picCanvas');
              that.setData({
                picCanvasWidth: res.width,
                picCanvasHeight: res.height,
              })
              that.resetCanvas(context,res.width,res.height);
              context.drawImage(res.path,0, 0);
              context.draw(false,function(drawed){
                  // console.log(drawed);
                  wx.canvasToTempFilePath({
                      x: 0,
                      y: 0,
                      width: res.width,
                      height: res.height,
                      destWidth: res.width,
                      destHeight:res.height,
                      fileType: 'jpg',
                      canvasId: 'picCanvas',
                      success(imgRes) {
                          console.log('-----------'+imgRes.tempFilePath)
                          that.setData({
                            files: [imgRes.tempFilePath]
                          });
                          console.log(that.data.files)
                          that.setData({
                            buttonText: '查看 / 编辑'
                          })
                      },
                      fail() {
                          that.setData({
                              isSignCanvasShow:false
                          })
                          that.setData({
                            buttonText: '解析图片失败，请重传'
                          })
                          
                      }
                  })
              } )
          }
      })
        
      }
    })
  },

  accountLogin: function() {
    if(this.data.buttonText == '解析图片中...'){
      return
    }
    
    var that = this;
    var path = that.data.files[0]
    var url = '/pages/picInfo/picInfo?path='+path
    
    wx.navigateTo({
      url: url,
    })
    that.setData({
      files: []
    })
    
    
  },

  generateUUID() {
    var d = new Date().getTime(); //Timestamp
    var d2 =  0; //Time in microseconds since page-load or 0 if unsupported
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16; //random number between 0 and 16
        if(d > 0) { //Use timestamp until depleted
            r = (d + r)%16 | 0;
            d = Math.floor(d/16);
        } else { //Use microseconds since page-load if supported
            r = (d2 + r)%16 | 0;
            d2 = Math.floor(d2/16);
        }
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
  },

  bindTitleInput: function(e) {
    console.log('------------')
    this.setData({
      title: e.detail.value
    });
  },

  bindAuthor_nameInput: function(e) {

    this.setData({
      author_name: e.detail.value
    });
  },

  bindVersionInput: function(e) {

    this.setData({
      version: e.detail.value
    });
  },

  onShareAppMessage: function() {
    let userInfo = wx.getStorageSync('userInfo');
    let shareUserId = 1;
    if (userInfo){
      shareUserId = userInfo.userId;
    }
    console.log('/pages/index/index?shareUserId=' + shareUserId);
    return {
      title: '一站式软著说明书文档生成平台',
      desc: '',
      path: '/pages/index/index?shareUserId=' + shareUserId
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  getIndexData: function() {
    
  },
  onLoad: function(options) {
    this.setData({
      colseCoupon: false
    });
    //如果有分享用户，则设置
    if (options.shareUserId){
      wx.setStorageSync('shareUserId', options.shareUserId);
    }

    
    this.getIndexData();
  },
  onReady: function() {
    
  },
  onShow: function() {
    

  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  onColse: function () {
    this.setData({
       window: false,
       colseCoupon:true
     });
  },

})